<template>
  <base-breadcrumb>
    <a-tabs type="card" v-model="activeKey" @change="tabChange">
      <a-tab-pane key="1" tab="项目产值记录">
        <searchData ref="searchData" :searchData="searchArr" @search="search"></searchData>

        <a-card :bordered="false" style="minHeight: 400px">
          <!-- <title-name title="项目产值信息列表"></title-name> -->
          <a-button class="mb12" type="primary" @click="dialogVisibleType = 'exportBaseVal'">导出基础产值数据</a-button>
          <a-button class="ml12" type="primary" @click="dialogVisibleType = 'exportCompanyVal'">导出公司汇总数据</a-button>
          <!-- <div class="pub-table-select-count">
            <a-icon type="info-circle" theme="twoTone" />
            <span style="margin-right: 12px">
              项目总数：<span class="totalNum">{{ totalSize }} 个</span></span
            >
          </div> -->

          <s-table
                  row-key="orgId"
                  ref="table"
                  size="default"
                  :scroll="{x: true}"
                  :columns="columns"
                  :data="loadData"
                  :children-column-name="'childTree'"
                  :alert="true"
                  show-size-changer
                  show-quick-jumper
                  :showPagination="false"
                  :expanded-row-keys="expandedRowKeys"
                  @expand="expandedRowsChange"
          >
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
            <span slot="action" slot-scope="text, record">
          <template v-if="record.tageCode === 'PD'">
            <!-- 待确认 -->
            <MoreButton>
            <a @click="handleDels(record)" v-btnPermission="[{code:'seex_pm_029_loo_01',ident:'prma_seex'},{code:'buco_pm_029_loo_01',ident:'prma_buco'}]">查看</a>
            <a @click="handleEdit(record)" v-btnPermission="[{code:'seex_pm_029_rec_02',ident:'prma_seex'},{code:'buco_pm_029_rec_02',ident:'prma_buco'}]">产值记录</a>
            <!-- <a @click="handleDels(record)" v-btnPermission="'pm_029_loo_01'">查看</a>
            <a-divider type="vertical" v-btnPermission="'pm_029_loo_01'" />
            <a @click="handleEdit(record)" v-btnPermission="'pm_029_rec_02'">产值记录</a> -->
              </MoreButton>
          </template>
        </span>
          </s-table>
        </a-card>
      </a-tab-pane>
      <a-tab-pane key="2" tab="产值数据统计">
        <outputDataStatistics></outputDataStatistics>
      </a-tab-pane>
      <a-tab-pane key="3" tab="目标产值">
        <targetOutputValue></targetOutputValue>
      </a-tab-pane>
      <a-tab-pane key="4" tab="计划产值">
        <plannedOutputValue></plannedOutputValue>
      </a-tab-pane>
    </a-tabs>
    <!-- 导出 -->
    <a-modal :visible.sync="visible" title="导出" @cancel="visible = false" width="600px">
      <a-row type="flex" :gutter="12">
        <a-col :span="12">
          <a-row type="flex" :gutter="12">
            <a-col :span="4"
              ><div align="right"><b>年月:</b></div></a-col
            >
            <a-col :span="20">
              <span v-if="monthes.length === 0">请选择年月</span>
              <a-tag closable @close="monthes = monthes.filter((i) => i !== item)" v-for="item in monthes" :key="item" style="margin-bottom: 6px"> {{ item }}</a-tag>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="12">
          <a-month-picker @change="(e) => !monthes.some((i) => i === e) && monthes.push(e)" format="YYYY-MM" valueFormat="YYYY-MM" :open="visible" style="height: 300px">
            <div></div>
          </a-month-picker>
        </a-col>
      </a-row>
      <div slot="footer" class="btn_box">
        <excel ref="exportAll" fileName="项目产值" is-click-generate="false">
          <a-button :loading="loading" slot="excelBtn" @click="exportAll">导出</a-button>
        </excel>
        <!-- 关闭 -->
        <a-button type="primary" @click="visible = false">关闭</a-button>
      </div>
    </a-modal>

    <BaseDialog :dialogVisibleType.sync="dialogVisibleType"></BaseDialog>
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getProjectOutputList, exportDatas } from '@/api/project/productionRecords'
import outputDataStatistics from "./components/outputDataStatistics"
import targetOutputValue from "./components/targetOutputValue"
import plannedOutputValue from "./components/plannedOutputValue"
import constructionSchedule from '@/api/construction/constructionSchedule'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import OrgTreeSelect from '@/components/OrgTreeSelect'

import BaseDialog from './BaseDialog.vue'

import ARow from 'ant-design-vue/es/grid/Row'

const searchArr = [
  // 搜索框
  {
    name: '所属单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
  },
  // {
  //   name: '项目名称',
  //   value: 'projectName',
  //   type: 'input'
  // },
  {
    name: '项目状态',
    value: 'statusSet',
    type: 'selectMode',
    data: [
      {
        value:1,
        label: "施工准备阶段"
      },
      {
        value:2,
        label: "在建"
      },
      {
        value:3,
        label: "停工"
      },
      {
        value:4,
        label: "停缓建"
      },
      {
        value:5,
        label: "维保期"
      },
      {
        value:6,
        label: "维保期截止"
      }
    ]
  }
]

const columns = [
  {
    title: '项目名称',
    width: 320,
    dataIndex: 'projectName',
    ellipsis: true,
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.projectName
        return text ? text : ''
      } else {
        return row.orgName
        // return row.orgName + ' ' + row.total
      }
    }
  },
  {
    title: '项目编号',
    dataIndex: 'projectCode',
    width: 120,
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.projectCode
        return text ? text : ''
      } else {
        return ''
      }
    }
  },
  {
    title: '项目状态',
    width: 100,
    dataIndex: 'projectStatus',
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.projectStatus
        return (text ?? '') !== '' ? text : ''
      } else {
        return ''
      }
    }
  },

  {
    title: '合同额（亿元）',
    dataIndex: 'contractAmount',
    width: 140,
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.contractAmount
        return (text ?? '') !== '' ? text : ''
      } else {
        return ''
      }
    }
  },
  {
    title: '开工累计确权产值（亿元）',
    dataIndex: 'confirmTotalOutput',
    width: 220,
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.confirmTotalOutput
        return (text ?? '') !== '' ? text : ''
      } else {
        return ''
      }
    }
  },
  {
    title: '全年产值指标（万元）',
    width: 180,
    dataIndex: 'yearPlanOutput',
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.yearPlanOutput
        return (text ?? '') !== '' ? text : ''
      } else if (row.tageCode === 'CO' || row.tageCode === 'BC') {
        const text = row?.yearPlanOutput
        return (text ?? '') !== '' ? text : ''
      } else {
        return ''
      }
    }
  },
  {
    title: '自年初累计实际产值（万元）',
    width: 220,
    dataIndex: 'yearActualOutput',
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.yearActualOutput
        return (text ?? '') !== '' ? text : ''
      } else if (row.tageCode === 'CO' || row.tageCode === 'BC') {
        const text = row?.yearActualOutput
        return (text ?? '') !== '' ? text : ''
      } else {
        return ''
      }
    }
  },
  {
    title: '自年初累计确认产值（万元）',
    dataIndex: 'yearConfirmOutput',
    width: 220,
    customRender: (value, row) => {
      if (row.tageCode === 'PD') {
        const text = row.projectVO?.yearConfirmOutput
        return (text ?? '') !== '' ? text : ''
      } else if (row.tageCode === 'CO' || row.tageCode === 'BC') {
        const text = row?.yearConfirmOutput
        return (text ?? '') !== '' ? text : ''
      } else {
        return ''
      }
    }
  },
  // {
  //   title: '年度确权产值完成率（%）',
  //   width: 200,
  //   dataIndex: 'yearConfirmOutputRate',
  //   customRender: (value, row) => {
  //     if (row.tageCode === 'PD') {
  //       const text = row.projectVO?.yearConfirmOutputRate
  //       return (text ?? '') !== '' ? text : ''
  //     } else if (row.tageCode === 'CO' || row.tageCode === 'BC') {
  //       const text = row?.yearConfirmOutputRate
  //       return (text ?? '') !== '' ? text : ''
  //     } else {
  //       return ''
  //     }
  //   }
  // },
  {
    title: '操作',
    dataIndex: 'action',
    width: 220,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'ProductionRecords',
  components: {
    ARow,
    STable,
    BaseDialog,
    outputDataStatistics,
    targetOutputValue,
    plannedOutputValue
  },
  data() {
    return {
      activeKey: '1',
      // 默认展开项
      expandedRowKeys: [],
      dialogVisibleType: '',
      columns,
      searchArr,
      businessId: 'PM10',
      visible: false,
      monthes: [],
      title: '',
      totalSize: '', // 项目总数

      form: {}, // 新增停工
      queryParam: {
        projectCode: '',
        projectName: ''
      },

      data: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: async (parameter) => {
        try {
          const {
            data: { treeVO, total, expandedRowKeys }
          } = await getProjectOutputList(this.queryParam)
          this.totalSize = total
          this.expandedRowKeys = expandedRowKeys
          return Promise.resolve({
            data: treeVO ? [treeVO] : []
          })
        } catch (error) {
          console.log(error)
          return Promise.reject(error)
        }
        // const requestParameters = Object.assign({}, parameter, this.queryParam)
        // return getProjectOutputList(requestParameters).then((res) => {
        //   this.totalSize = res.totalSize
        //   return res
        // })
      },
      selectedRowKeys: [],
      selectedRows: [],
      reasons: [],
      totalDels: {},
      loading: false,
      columnsExport: [
        {
          title: '序号',
          width: 65,
          dataIndex: 'index'
        },
        {
          title: '项目名称',
          dataIndex: 'projectName'
        },
        {
          title: '分公司名称',
          dataIndex: 'branchCompanyName'
        },
        {
          title: '月份',
          dataIndex: 'month'
        },
        {
          title: '当月项目人数',
          dataIndex: 'projectPeopleNumber'
        },
        {
          title: '当月计划总产值(万)',
          dataIndex: 'planGrossOutput'
        },
        {
          title: '当月计划人均产值(万)',
          dataIndex: 'planPerCapita'
        },
        {
          title: '当月实际总产值(万)',
          dataIndex: 'realGrossOutput'
        },
        {
          title: '当月实际人均产值(万)',
          dataIndex: 'realPerCapita'
        },
        {
          title: '当月确权总产值(万)',
          dataIndex: 'authenticRightGrossOutput'
        },
        {
          title: '当月确权人均产值(万)',
          dataIndex: 'authenticRightPerCapita'
        },
        {
          title: '当年至本月计划总产值(万)',
          dataIndex: 'thatYearToThatMonthPlanGrossOutput'
        },
        {
          title: '当年至本月计划人均(万)',
          dataIndex: 'thatYearToThatMonthPlanPerCapita'
        },
        {
          title: '当年至本月实际总产值(万)',
          dataIndex: 'thatYearToThatMonthRealGrossOutput'
        },
        {
          title: '当年至本月实际人均产值(万)',
          dataIndex: 'thatYearToThatMonthRealPerCapita'
        },
        {
          title: '当年至本月确权总产值(万)',
          dataIndex: 'thatYearToThatMonthAuthenticRightGrossOutput'
        },
        {
          title: '当年至本月确权人均产值(万)',
          dataIndex: 'thatYearToThatMonthAuthenticRightPerCapita'
        },
        {
          title: '开工至本月实际总产值(万)',
          dataIndex: 'startWorkToThatMonthRealGrossOutput'
        },
        {
          title: '开工至本月确权人均产值(万)',
          dataIndex: 'startWorkToThatMonthAuthenticRightGrossOutput'
        }
      ]
    }
  },
  watch: {
    visible(e) {
      if (e) {
        this.$nextTick(() => {
          this.monthes = []
          this.$refs.exportAll.tableToExcelFile({ columns: this.columnsExport })
        })
      }
    }
  },
  created() {
    this.activeKey = this.$route.query.activeKey || '1'
  },
  computed: {},
  methods: {
    tabChange(activeKey) {
      this.$router.replace({
        path: '/project/productionRecord',
        query: {
          query: this.$route.query.query,
          activeKey
        }
      })
    },
    /**
     * @description: 手动展开
     * @param {boolean} expanded 是否展开
     * @param {object} record 行
     * @return {void}
     */
    expandedRowsChange(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.orgId)
      } else {
        this.expandedRowKeys.splice(
          this.expandedRowKeys.findIndex((el) => el === record.orgId),
          1
        )
      }
    },
    exportAll() {
      this.loading = true
      exportDatas(Object.assign({}, { month: this.monthes.join(',') }, this.$refs.searchData.form.getFieldsValue()))
        .then((res) => {
          res.data.forEach((item, index) => {
            item.index = index
          })
          this.loading = false
          this.$refs.exportAll.setDataAndGenerate(res.data)
          this.$message.success('导出成功')
          this.visible = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    search(val) {
      this.queryParam = val
      this.$refs.table.refresh(true)
    },

    handleEdit(e) {
      this.$router.push({ path: '/project/productionRecord/details', query: { id: e.projectVO.id, isDetails: 0 } })
    },

    handleDels(e) {
      this.$router.push({ path: '/project/productionRecord/details', query: { id: e.projectVO.id, isDetails: 1 } })
    }
  }
}
</script>

<style scoped lang="less">
  /deep/ .ant-tabs-bar {
    margin-bottom: 0;
  }
</style>


